<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Home extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }

    /**
     * 获取about表数据：
     * type：1 注册协议    2 隐私协议    3 关于我们    4 我的页面的背景图
     * @return string
     */
    public function getAbout()
    {
        extract(input());
        $res = Db::table('up_about')
            ->where('id',$type)
            ->find();
        return json(['status'=>200,'msg'=>$res]);
    }
    /**
     * location 自动定位返回id：location
     * $location  地区名称
     */
    public function locationGet (){
        extract(input());
        $res = array();
        if(isset($sheng)){
            $shengID = Db::table('up_area')
                ->where('district',$sheng)
                ->where('level',1)
                ->value('district_id');
            $res['sheng'] = $shengID;
        }
        if(isset($shi)){
            $shiID = Db::table('up_area')
                ->where('district',$shi)
                ->where('level',2)
                ->value('district_id');
            $res['shi'] = $shiID;
        }
        if(isset($qu)){
            $quID = Db::table('up_area')
                ->where('district',$qu)
                ->where('level',3)
                ->value('district_id');
            $res['qu'] = $quID;
        }
        return json(['status'=>200,'msg'=>$res]);
    }

    /**
     * 获取足球或篮球下的分类
     * fid：1足球  2篮球
     * @return \think\response\Json
     */
    public function getTypes()
    {
        extract(input());
        if(!isset($fid) || !$fid){
            $fid = 1;
        }
        $data = Db::table('up_news_type')
            ->where('nt_fid',$fid)
            ->order('nt_sort desc')
            ->field('nt_id,nt_name')
            ->select();
        Db::table('up_u_user')->where('user_id',$user_id)->setField('user_logintime',date('Y-m-d H:i:s'));
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取首页初始数据：轮播图和赛事
     * nt_id：顶部小分类id
     */
    public function getHomeData(){
        extract(input());
        if(!isset($fid) || !$fid){
            $fid = 1;
        }
        //1、轮播
        $lunbo = Db::table('up_banner')
            ->where('banner_type',1)
            ->where('banner_type_id',$nt_id)
            ->where('banner_status',1)
            ->order('banner_sort desc')
            ->field('banner_id,banner_img,banner_title')
            ->select();
        //2、赛事
        $typeData = $this->getTableData('up_news_type',['nt_id' => $nt_id]);
        if($typeData['nt_type'] == 2){
            $where = [
                'mf_fid' => $fid ,
                'mf_fj_matchid' => ['in',"{$typeData['nt_one']},{$typeData['nt_two']}"]
            ];
        }else{
            $where = [
                'mf_id' => ['>',0] ,
                'mv_id' => ['>',0] ,
                'mf_fid' => $fid ,
                'mf_name' => $typeData['nt_name'] ,
                'mf_state' => ['>=',0] ,
//                'mf_match_time' => 'today' ,
            ];
        }
        $field = 'mf_id,mv_id,mf_state,mf_match_time,mf_name,mf_home_id,mf_away_id,mf_home_name_cn,mf_away_name_cn,mf_json';
        $match = $this->matchDatas($where,'mf_state desc,mf_match_time asc',1,2,$field);
        if($match){
            foreach ($match as $k => $v){
                $match[$k]['home_logo'] = Db::table('up_sport')
                    ->where('sport_fid',$fid)
                    ->where('sport_team_id',$v['mf_home_id'])
                    ->value('sport_logo');
                $match[$k]['away_logo'] = Db::table('up_sport')
                    ->where('sport_fid',$fid)
                    ->where('sport_team_id',$v['mf_away_id'])
                    ->value('sport_logo');
                $decodeData = json_decode($v['mf_json'],true);
                $match[$k]['mf_home_score'] = $decodeData['homeScore'];
                $match[$k]['mf_away_score'] = $decodeData['awayScore'];
            }
        }
        return json(['status'=>200,'msg'=>$lunbo,'match'=>$match]);
    }
    /**
     * 获取首页资讯数据：getHomeNews
     * nt_id：顶部小分类id
     */
    public function getHomeNews(){
        extract(input());
        if(!isset($fid) || !$fid){
            $fid = 1;
        }
        //3、资讯
        $where = [
            'new_fid' => $fid ,
            'new_type' => $nt_id,
            'new_status' => 1
        ];
        $news = Db::table('up_news')
            ->where($where)
            ->order('new_update desc')
            ->field('new_id,new_title,new_thumb,new_sign_left,new_sign_right,new_video,new_comment,new_zan')
            ->page($page,10)
            ->select();
        return json(['status'=>200,'msg'=>$news]);
    }

    /**
     * 轮播图详情：lunboInfo
     * banner_id
     */
    public function lunboInfo(){
        extract(input());
        $data = $this->getTableData('up_banner',['banner_id' => $banner_id]);
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 资讯详情：newInfo
     * new_id
     */
    public function newInfo(){
        extract(input());
        $data = $this->getTableData('up_news',['new_id' => $new_id]);
        if($data['new_status'] != 1){
            return json(['status'=>0,'msg'=>'资讯不存在']);
        }
        $zan = $this->getTableData('up_zan',['zan_type' => 1,'zan_new_com_id' => $new_id,'zan_user_id' => $user_id]);
        $data['zan'] = 1; //我没有赞
        if($zan){
            $data['zan'] = 2;
        }
        //---------入浏览记录-------
        $today = date('Y-m-d H:i:s');
        $have = $this->getTableData('up_news_history',['his_new_id' => $new_id,'his_user_id' => $user_id]);
        if($have){
            Db::table('up_news_history')->where('his_id',$have['his_id'])->setField('his_time',$today);
        }else{
            Db::table('up_news_history')->insert([
                'his_new_id' => $new_id,
                'his_user_id' => $user_id,
                'his_time' => $today
            ]);
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 获取资讯里的评论和回复：getComments
     * for_id：资讯id或社区帖子id
     * comment_type：1资讯  2社区
     *
     */
    public function getComments()
    {
        extract(input());
        $comment = Db::table('up_comment')
            ->join('up_u_user', 'user_id = comment_reply_user_id', 'left')
            ->field('user_id,user_username, user_image, comment_id, comment_content, comment_time,comment_zan')
            ->where('comment_type', $comment_type)
            ->where('comment_new_id', $for_id)
            ->order('comment_time desc')
            ->page($page, 10)
            ->select();
        if($comment){
            $zanType = 2;
            if($comment_type == 2) $zanType = 4;
            foreach ($comment as $k => $v){
                //1、我有没有点过评论的赞
                $comment[$k]['zan'] = 1;
                $zan = $this->getTableData('up_zan',['zan_type' => $zanType,'zan_new_com_id' => $v['comment_id'],'zan_user_id' => $user_id]);
                if($zan){
                    $comment[$k]['zan'] = 2;
                }
                //2、评论里的回复内容
                $field = 'u.user_id one_id,u2.user_id reply_id,u.user_username one_name,u2.user_username reply_name';
                $field .= ',comtt_id,comtt_content,comtt_time,comtt_reply_user_id,u.user_image one_image,u2.user_image reply_image';
                $reply = Db::table('up_comment_tt')->alias('m')
                    ->join('up_u_user u','m.comtt_one_user_id=u.user_id','LEFT')
                    ->join('up_u_user u2','m.comtt_reply_user_id=u2.user_id','LEFT')
                    ->where('comtt_comment_id',$v['comment_id'])
                    ->field($field)
                    ->order('comtt_time DESC')
                    ->select();
                $comment[$k]['reply'] = $reply;
            }

        }
        return json(['status' => 200, 'msg' => $comment]);
    }
    /**
     * 点赞
     * zan_type：1资讯点赞 2资讯评论点赞 3社区帖子点赞 4帖子评论点赞
     * for_id：对应的id
     *
     */
    public function dianzan(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $have = $this->getTableData('up_zan',['zan_type' => $zan_type,'zan_new_com_id' => $for_id,'zan_user_id' => $user_id]);
        Db::startTrans();
        try {
            if($have){
                Db::table('up_zan')->where('zan_id',$have['zan_id'])->delete();
                if($zan_type == 1) Db::table('up_news')->where('new_id',$for_id)->setDec('new_zan',1);
                if($zan_type == 2 || $zan_type == 4) Db::table('up_comment')->where('comment_id',$for_id)->setDec('comment_zan',1);
                if($zan_type == 3) Db::table('up_talks')->where('t_id',$for_id)->setDec('t_zan',1);
            }else{
                $insert = [
                    'zan_type' => $zan_type,
                    'zan_new_com_id' => $for_id,
                    'zan_user_id' => $user_id,
                    'zan_time' => $today
                ];
                Db::table('up_zan')->insert($insert);
                if($zan_type == 1) Db::table('up_news')->where('new_id',$for_id)->setInc('new_zan',1);
                if($zan_type == 2 || $zan_type == 4) Db::table('up_comment')->where('comment_id',$for_id)->setInc('comment_zan',1);
                if($zan_type == 3) Db::table('up_talks')->where('t_id',$for_id)->setInc('t_zan',1);
            }
            Db::commit();
            return json(['status'=>200,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>0,'msg'=>'操作失败，请刷新重试']);
        }
    }
    /**
     * 发布评论
     * @return \think\response\Json
     * comment_type：1资讯  2社区
     */
    public function writeReport(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        $insert = [
            'comment_type' => $comment_type,
            'comment_new_id' => $for_id,
            'comment_content' => $comment_content,
            'comment_reply_user_id' => $user_id,
            'comment_time' => $today,
        ];
        Db::startTrans();
        try{
            // 评论
            Db::table('up_comment')->insert($insert);
            // 评论数量加一
            if($comment_type == 1) Db::table('up_news')->where('new_id', $for_id)->setInc('new_comment');
            if($comment_type == 2) Db::table('up_talks')->where('t_id', $for_id)->setInc('t_comment');
            Db::commit();
            return json(['status' => 200, 'msg' => '评论成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '评论失败']);
        }
    }
    /**
     * 回复评论
     * @return \think\response\Json
     * 如果直接回复的评论，one_id不传即可，如果回复的是评论里面的回复，one_id就是你回复的那个人的id（即此评论回复列表里的one_id）
     */
    public function replyToComment(){
        extract(input());
        $today = date('Y-m-d H:i:s');
        if(!isset($one_id) || !$one_id){
            $one_id = 0;
        }
        $insert = [
            'comtt_comment_id' => $comment_id,
            'comtt_one_user_id' => $user_id,
            'comtt_reply_user_id' => $one_id,
            'comtt_content' => $comtt_content,
            'comtt_time' => $today
        ];
        $res = Db::table('up_comment_tt')->insert($insert);
        if($res){
            return json(['status' => 200, 'msg' => '回复成功']);
        }else{
            return json(['status' => 100, 'msg' => '回复失败']);
        }
    }
    /**
     * 生成省市区json数据：makeJson
     * @return string
     */
    public function makeJson()
    {
//        set_time_limit(0);
//        $area = file_get_contents('static/area.json');
//        $area2 = json_decode($area,true);
//        return json($area2);
        set_time_limit(0);
        $pro = Db::table('up_area')
            ->where('pid',0)
//            ->where('district_id',1001)
            ->field('district_id id,district name')
            ->order('sort')
            ->select();
        foreach($pro as $k=>$v){
            $pro[$k]['parentId'] = 0;
            $city = Db::table('up_area')
                ->where('pid',$v['id'])
                ->where('level',2)
                ->field('district_id id,district name,pid parentId')
                ->select();
//            foreach ($city as $kk=>$vv){
//                $city[$kk]['sub'] = Db::table('up_area')
//                    ->where('pid',$vv['id'])
//                    ->where('level',3)
//                    ->field('district_id id,district name,pid parentId')
//                    ->select();
//            }
            $pro[$k]['sub'] = $city;
        }
        return json($pro);
    }
}